package com.commonlib.downloadmgr.base;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Map;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
 * Various helper functions
 * 
 */
public abstract class DownloadBaseHelper<T> {
	private static final String TAG = DownloadBaseHelper.class.getSimpleName();
	private static final String SUFFIX_TEMP = ".temp";
	
	/**
	 * 创建本地下载文件名，用于生成目标下载文件
	 * @param context
	 * @param job
	 * @return
	 */
	public File getDownloadFile(Context context, DownloadBaseJob<T> job){
		File retval = null;
		File dir = getDownloadDir(context, job);
		if (dir != null) {
			if (!dir.exists() && !dir.mkdirs()) {
				retval = null;
			}else{
				retval = new File(dir, getFileName(job) + getFileSuffix(job));
			}
		}
//		Log.v(TAG, "getDownloadFile, retval is " + retval==null?"null":retval.getAbsolutePath());
		return retval;
	}
	
	/**
	 * 创建临时下载文件，用于临时存储下载内容，下载完毕后，重命名为目标文件
	 * @param context
	 * @param job
	 * @return
	 */
	public File getDownloadFileTemp(Context context, DownloadBaseJob<T> job){
		File retval = null;
		File dir = getDownloadDir(context, job);
		if (dir != null) {
			if (!dir.exists() && !dir.mkdirs()) {
				retval = null;
			}else{
				retval = new File(dir, getFileName(job) + SUFFIX_TEMP);
			}
		}
//		Log.v(TAG, "getDownloadFileTemp, retval is " + retval==null?"null":retval.getAbsolutePath());
		return retval;
	}
	
	/**
	 * 获取下载文件大小，优先临时文件，其次目标文件
	 * @param context
	 * @param job
	 * @return
	 */
	public int getDownloadFileSize(Context context, DownloadBaseJob<T> job) {
		int retval = 0;
		File tempFile = getDownloadFileTemp(context, job);
		File file = getDownloadFile(context, job);
		File curFile;
		if (tempFile!=null && tempFile.exists()) {
			curFile = tempFile;
		} else{
			curFile = file;
		}
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(curFile);
			retval = fis.available();
			fis.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		Log.v(TAG, "getDownloadFileSize, retval is " + retval);
		return retval;
	}
	
	/**
	 * 删除临时以及目标下载文件，如果它们存在的话。
	 * @param context
	 * @param job
	 */
	public void deleteDownloadedFile(Context context, DownloadBaseJob<T> job){
		File tempFile = getDownloadFileTemp(context, job);
		File file = getDownloadFile(context, job);
		if (tempFile!=null && tempFile.exists()) {
			tempFile.delete();
			Log.v(TAG, "deleteDownloadedFile, tempFile is " + tempFile.getAbsolutePath());
		}
		if (file != null && file.exists()) {
			file.delete();
			Log.v(TAG, "deleteDownloadedFile, file is " + file.getAbsolutePath());
		}
	}
	

	/**
	 * 是否已连接WIFI
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isWiFiConnected(Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity != null) {
			NetworkInfo info = connectivity.getActiveNetworkInfo();
			if (info != null) {
				if (info.getTypeName().equals("WIFI") && info.isConnected()) {
					return true;
				}
			}
		}
		return false;
	}
	
	/**
	 * 当前是否有可用网络
	 * @param context
	 * @return
	 */
	public static boolean isNetworkOk(Context context) {  
	    ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 
	    if (connectivity == null) {     
	      return false; 
	    } else {   
	        NetworkInfo[] infos = connectivity.getAllNetworkInfo();     
	        if (infos != null) {         
	            for (int i = 0; i < infos.length; i++) {            
	                if (infos[i].getState() == NetworkInfo.State.CONNECTED) {               
	                    return true;  
	                }         
	            }      
	        }  
	    }    
	    return false; 
	}	
	
	/**
	 * 下载大小单位适配
	 * @param bytes
	 * @return
	 */
	public static String formatSizeUnit(long bytes){
		String retval = "0Mb";
		DecimalFormat dcmfmt = new DecimalFormat("0.00");
		double sizeKb = bytes/1024;
		if (sizeKb > 0 && sizeKb < 1000) {
			retval = dcmfmt.format(sizeKb) + "Kb";
		}else if(sizeKb > 1000){
			retval = dcmfmt.format(sizeKb/1024) + "Mb";
		}
		return retval;
	}
	
	protected abstract String getFileName(DownloadBaseJob<T> job);
	
	protected abstract String getFileSuffix(DownloadBaseJob<T> job);
	
	protected abstract File getDownloadDir(Context context, DownloadBaseJob<T> job);

	public abstract void showNotifcation(DownloadBaseJob<T> job);
	
	public abstract void cancelNotifcation(DownloadBaseJob<T> job);
	
	public abstract Map<String, String> getHeadParameter();
}
